package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.itheima.common.PageInfo;
import com.itheima.common.ThreadLocalIUtil;
import com.itheima.dto.DishDto;
import com.itheima.dto.FlavorDto;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Flavor;
import com.itheima.service.DishService;
import com.itheima.vo.DishVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public PageInfo<DishVo> page(String name ,Integer page, Integer pageSize,Integer type) {
        PageInfo<DishVo> pageInfo = new PageInfo<>();
        Integer start = (page - 1) * pageSize;
        List<Dish> dishs = dishMapper.page( name,start, pageSize,type);

        List<DishVo> newdishVo=new ArrayList<>();
        for (Dish dish : dishs) {
            DishVo dishVo=new DishVo();
            BeanUtils.copyProperties(dish, dishVo);

            String categoryId = dish.getCategoryId();
            Category categorybyId = categoryMapper.getById(categoryId);
            dishVo.setCategoryName(categorybyId.getName());

            newdishVo.add(dishVo);

        }
        pageInfo.setRecords(newdishVo);
        pageInfo.setSize(pageSize);
        pageInfo.setCurrent(page);
        long count = dishMapper.count();
        pageInfo.setTotal(count);
        return pageInfo;
    }

    // 口味添加失败回滚
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean save(DishDto dishDto) {

        // 获取category表上的id
        String categoryId = dishDto.getCategoryId();
        // 判断id是否存在
        Category category = categoryMapper.getById(categoryId);
        if (category == null) {
            return false;
        }


        Dish dish = new Dish();
        String dishId = IdUtil.getSnowflakeNextIdStr();
        dishDto.setId(dishId);
        BeanUtils.copyProperties(dishDto, dish);
        dish.setCreateUser(ThreadLocalIUtil.getId());
        dish.setCategoryId(categoryId);
        int adddish = dishMapper.save(dish);

        // 口味信息 ->口味表
        // 1.获取当前菜品的口味集合
        List<FlavorDto> flavors = dishDto.getFlavors();

        List<Flavor> newlist = new ArrayList<>();
        Flavor flavor = new Flavor();

        // 如果用循环+插入的方式，当我调用一次接口后，就会重复执行多次sql操作
        // 导致性能下降   todo不理解啊
        if (!CollectionUtil.isEmpty(flavors)) {
            // 2.遍历集合到数据库中
            for (FlavorDto item : flavors) {
                if (item == null) {
                    continue;
                }

                BeanUtils.copyProperties(item, flavor);
                flavor.setDishId(dishDto.getId());
                String flavorId = IdUtil.getSnowflakeNextIdStr();
                flavor.setId(flavorId);
                // 2.2 执行inset插入到数据库中
                // int rs = dishMapper.insertFlavor(flavor);
                // if (rs!=1){
                //     throw new RuntimeException("口味添加失败");
                // }
                newlist.add(flavor);
            }
        }
        // 批量插入口味信息
        int rs = dishMapper.batchInsertFlavor(newlist);
        if (rs != newlist.size()) {
            throw new RuntimeException("口味添加失败");
        }

        return adddish == 1;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean update(DishDto dishDto) {

        log.info("修改菜单id是：", dishDto.getId());

        if (dishDto == null) {
            throw new RuntimeException("参数不能为空");
        }

        DishVo dishVO = new DishVo();
        BeanUtils.copyProperties(dishDto, dishVO);
        LocalDateTime ldt = LocalDateTime.now();
        dishVO.setUpdateTime(ldt);

        dishVO.setCreateUser(ThreadLocalIUtil.getId());
        Integer update = dishMapper.update(dishVO);
        if (update == 0) {
            log.error("菜品添加失败");
            return false;
        }
        // 更新菜品与口味的关系
        int total = dishMapper.countFlavorByDishId(dishVO.getId());
        if (total > 0) {
            int removeResult = dishMapper.removeFlavorByDishId(dishDto.getId());
            if (removeResult == 0) {
                throw new RuntimeException("口味删除失败");
            }
        }


        List<FlavorDto> flavors = dishDto.getFlavors();
        List<Flavor> newlist = new ArrayList<>();

        // 如果用循环+插入的方式，当我调用一次接口后，就会重复执行多次sql操作
        // 导致性能下降   todo不理解啊
        if (!CollectionUtil.isEmpty(flavors)) {

            // 2.遍历集合到数据库中
            for (FlavorDto item : flavors) {

                if (item == null) {
                    continue;
                }

                Flavor flavor = new Flavor();
                BeanUtils.copyProperties(item, flavor);

                flavor.setDishId(dishDto.getId());
                String flavorId = IdUtil.getSnowflakeNextIdStr();
                flavor.setId(flavorId);
                newlist.add(flavor);
            }
        }
        // 批量插入口味信息
        int rs = dishMapper.batchInsertFlavor(newlist);
        if (rs != newlist.size()) {
            throw new RuntimeException("口味添加失败");
        }

        return (rs > 0 && update == 1);
    }


    @Override
    public List<DishVo> getList(String categoryId) {
        List<Dish> dishes = dishMapper.getList(categoryId);
        List<DishVo> dishVos=new ArrayList<>();

        for (Dish dish : dishes) {
            List<Flavor> flavor = getFlavorByDishId(dish.getId());
            DishVo dishVo=new DishVo();
            BeanUtils.copyProperties(dish, dishVo);
            dishVo.setFlavors(flavor);
            dishVos.add(dishVo);
        }


        return dishVos;
    }

    /**  按dishId菜单id 找到口味
     *
     */

    public List<Flavor> getFlavorByDishId(String dishId) {
        List<Flavor> flavor = dishMapper.getFlavorByDishId(dishId);
        return flavor;
    }

    @Override
    public boolean delete(List<String> ids) {

        Integer delete = dishMapper.delete(ids);
        return delete > 0;
    }

    @Override
    public DishVo getById(String id) {
        //todo 添加口味表
        DishVo dishvo = dishMapper.getById(id);

        if (dishvo == null) {
            return null;
        }

        dishvo.setFlavors(getFlavorByDishId(id));
        return dishvo;
    }


    @Override
    public boolean sell(List<String> ids, int status) {
        int sell = dishMapper.sell(ids, status);
        return sell == ids.size();
    }

    /**
     * 移动端按 分类Id查找菜单包含口味
     * @param categoryId
     * @param status
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public List<DishVo> clientGetList(String categoryId, Integer status, Integer page, Integer pageSize) {

        Integer start = (page - 1) * pageSize;
        List<Dish> dishes = dishMapper.clientGetList(categoryId, status, start, pageSize);
        List<DishVo> voList=new ArrayList<>();
        for (Dish dish : dishes) {
            DishVo dishVo=new DishVo();
            BeanUtils.copyProperties(dish,dishVo);

            List<Flavor> flavor = getFlavorByDishId(dish.getId());
            dishVo.setFlavors(flavor);
            voList.add(dishVo);
        }

        return voList;
    }

}
